package vip.liux.contracts.infrastructure.websocket;

import org.springframework.web.socket.WebSocketSession;
import vip.liux.core.current.ICurrentUser;

import java.util.Map;

/**
 * 专属于 web 包的工具类
 *
 * @author 芋道源码
 */
public class WebSocketFrameworkUtils {

    public static final String ATTRIBUTE_LOGIN_USER = "LOGIN_USER";

    /**
     * 设置当前用户
     *
     * @param currentUser 登录用户
     * @param attributes  Session
     */
    public static void setCurrentUser(ICurrentUser<Long> currentUser, Map<String, Object> attributes) {
        attributes.put(ATTRIBUTE_LOGIN_USER, currentUser);
    }

    /**
     * 获取当前用户
     *
     * @return 当前用户
     */
    @SuppressWarnings("unchecked")
    public static ICurrentUser<Long> getCurrentUser(WebSocketSession session) {
        return (ICurrentUser<Long>) session.getAttributes().get(ATTRIBUTE_LOGIN_USER);
    }

    /**
     * 获得当前用户的编号
     *
     * @return 用户编号
     */
    public static Long getCurrentUserId(WebSocketSession session) {
        ICurrentUser<Long> currentUser = getCurrentUser(session);
        return currentUser != null ? currentUser.getId() : null;
    }


    /**
     * 获得当前用户的类型
     *
     * @return 用户编号
     */
    public static String getCurrentTenant(WebSocketSession session) {
        ICurrentUser<Long> currentUser = getCurrentUser(session);
        return currentUser != null ? currentUser.getTenantId() : null;
    }
}
